package com.hong.concurrent.chapter6;

/**
 * @Author csh
 * @Description  共享数据
 * @Date 2018/7/1 16:01
 */
public class ShareData {
    /*存放数据数组长度*/
    private final char[] buffer;
    /*读写锁*/
    private final  ReadWriteLock lock = new ReadWriteLock();
    /*构造函数*/
    public ShareData(int size) {
        //初始化大小
        this.buffer= new char[size];
        /*循环*/
        for (int i = 0; i<size;i++){
            this.buffer[i]='*';
        }
    }

    /**
     * 读
     * @return
     */
    public char[] read() throws InterruptedException {
        try {
            lock.readLock();
            return this.doRead();
        }finally {
            lock.readUnlock();
        }
    }

    /**
     * 写
     */
    public void write(char c) throws InterruptedException {
        try {
            lock.writeLock();
            this.doWrite(c);
        }finally {
            lock.writeUnlock();
        }
    }

    /**
     * 写操作
     * @param c
     */
    private void doWrite(char c) {
        for (int i = 0; i<buffer.length;i++){
            buffer[i] =c;
            slowly(10);
        }
    }

    /**
     * 读操作
     * @return
     */
    private char[] doRead() {
        char[] newBuf = new char[buffer.length];
        for (int i = 0;i<buffer.length;i++){
            newBuf[i] = buffer[i];
        }
        slowly(500);
        return newBuf;
    }

    /**
     * 休眠
     * @param ms
     */
    private void slowly(int ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
